package se.lnu.axez;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import android.os.SystemClock;
import android.view.MotionEvent;

import se.lnu.axez.animation.Animation;

public class CompositeControl implements IControl {
	private final Transformation transformation;
	private final List<IControl> childControls;
	private final List<IControl> readOnlyChildrenList;
	private List<Animation<IControl>> activeAnimations;

	public CompositeControl() {
		this.transformation = new Transformation();
		this.childControls = new ArrayList<IControl>();
		this.readOnlyChildrenList = Collections.unmodifiableList(this.childControls);
	}
	
	public synchronized void addChild(IControl child) {
		if (child == null) {
			return;
		}
		
		if (!this.childControls.contains(child)) {
			this.childControls.add(child);
		}
	}

	public synchronized List<IControl> getChildren() {
		return this.readOnlyChildrenList;
	}

	public synchronized int getChildrenCount() {
		return this.childControls.size();
	}
	
	@Override
	public Transformation getTransformation() {
		return this.transformation;
	}

	@Override
	public synchronized void init(AxezContext context) {
		for (IControl child : this.childControls) {
			child.init(context);
		}
	}

	@Override
	public synchronized void draw(AxezContext context) {
		if (this.activeAnimations != null) {
			for(Iterator<Animation<IControl>> i = this.activeAnimations.iterator(); i.hasNext(); ) {
				Animation<IControl> animation = i.next();
				animation.animate(SystemClock.uptimeMillis(), this);
				if (animation.ended()) {
					i.remove();
				}
			}
		}

		RenderMatrices renderMatrices = context.getRenderMatrices();
		renderMatrices.pushModelViewMatrix();
		this.getTransformation().applyModelViewMatrix(renderMatrices);

		try {
			for (IControl child : this.childControls) {
				child.draw(context);
			}
		} finally {
			renderMatrices.popModelViewMatrix();
		}
	}

	@Override
	public void addAnimation(Animation<IControl> animation) {
		if (animation == null) {
			return;
		}

		if (this.activeAnimations == null) {
			this.activeAnimations = new ArrayList<Animation<IControl>>();
		}

		if (!this.activeAnimations.contains(animation)) {
			this.activeAnimations.add(animation);
		}
	}

	@Override
	public void onTouchEvent(MotionEvent motionEvent) {
	}
}
